package com.stwitinc.redmine.res.packageinsert;

import java.util.List;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.stwitinc.Logger;
import com.stwitinc.Util;
import com.stwitinc.redmine.LuceneUtil;
import com.stwitinc.redmine.dao.DAO;
import com.stwitinc.servlet.rest.RESTResource;
import com.stwitinc.servlet.rest.ResourceMethod;
import com.stwitinc.servlet.rest.ReturnType;

public class PackageInsertRes extends RESTResource
{
	private static final Logger logger = Logger.getLogger(PackageInsertRes.class);

	@ResourceMethod(returnType = ReturnType.JSON, validateToken = true)
	public JSONObject getSearchResult() throws Exception {
		JSONObject data = new JSONObject();
		data.put("count", 0);
		String keyword = getParameter("keyword");
		logger.debug("keyword=" + keyword);
		if (Util.isNullOrWhiteSpace(keyword)) {
			return data;
		}
		keyword = keyword.toLowerCase();
		try {
			List<Integer> medicineIdList = LuceneUtil.search(keyword);
			data.put("count", medicineIdList.size());
			JSONArray array = DAO.newMedicineDAO().getPackageInsertList(medicineIdList);
			for (int i = 0; i < array.size(); i++) {
				JSONObject rec = array.getJSONObject(i);
				int medicineId = rec.getIntValue("medicineId");
				String packageInsertUri = String.format("news/package_insert/%s", medicineId);
				rec.remove("medicineId");
				rec.put("packageInsertUri", packageInsertUri);
			}
			data.put("medicines", array);
			return data;
		} catch (Exception e) {
			JSONObject obj = new JSONObject();
			obj.put("error", -1);
			obj.put("message", e.getMessage());
			return obj;
		}
	}

	@ResourceMethod(returnType = ReturnType.FORWARD, validateToken = true)
	public String get(String medicineId) throws Exception {
		JSONObject obj = DAO.newMedicineDAO().getPackageInsertById(medicineId == null ? -1 : Integer.parseInt(medicineId));
		setAttribute("rec", obj);
		return "desktop/package-insert/package-insert.jsp";
	}
	
}
